var express = require('express');
var router = express.Router();
const db = require('../db/db');
const path = require("path");
const fs = require("fs");
let multer=require('multer')
let upload = multer({ dest: './public/uploads/img' })

router.use(upload.any());

router.post('/', function (req, res, next) {
    let {page, pageSize} = req.body;
    let start = (page - 1) * pageSize;
    let sql = `select id,name,type,detail,\`condition\`,starttime,endtime,\`require\`,path,
       (select count(*) from item) as total from item limit ${start},${pageSize}`
    db(sql, function (err, rows) {
        if (err) {
            res.render('error.html', {title: 'Express', datas: []});
        } else {
            res.json({datas: rows, total: rows[0]['total']});
        }
    })
});

router.post('/my', function (req, res, next) {
    let {page, pageSize} = req.body;
    let start = (page - 1) * pageSize;
    let tid = req.session.tid
    let sql = `select id,name,type,detail,\`condition\`,starttime,endtime,\`require\`,path,
       (select count(*) from item where t_id = ${tid}) as total from item where t_id = ${tid} limit ${start},${pageSize}`
    db(sql, function (err, rows) {
        if (err) {
            res.render('error.html', {title: 'Express', datas: []});
        } else {
            res.json({datas: rows, total: rows[0]['total']});
        }
    })
});

let filepath = ''
router.post('/upload', (req, res) => {
    let old_path = path.join(__dirname, '../public/uploads/img/' + req.files[0].filename);
    let ext = path.parse(req.files[0].originalname).ext;
    let filename = new Date().getTime();
    let new_path = path.join(__dirname, '../public/uploads/img/' + filename + ext);
    filepath = "/uploads/img/" + filename + ext;

    fs.rename(old_path, new_path, (err) => {
        if (err) {
            res.send('失败' + err)
        } else {
            console.log("上传成功")
        }
    })
})

router.post('/increase', (req, res) => {
    let {name, type, detail, condition, require, starttime, endtime} = req.body;
    let tid = req.session.tid
    let sql = `insert into item(name, type, detail, \`condition\`, \`require\`, starttime, endtime, path,t_id)
               values ('${name}', '${type}', '${detail}', '${condition}', '${require}', '${starttime}', '${endtime}',
                       '${filepath}',${tid})`;
    db(sql, function (err, result) {
        if (err) {
            res.send({flag: false, msg: "项目发布失败"});
            throw err;
        }
        res.send({flag: true, msg: "项目发布成功"});
    })
})

module.exports = router;